package dtos

import (
	"encoding/json"
	"errors"
	"log"
	"strconv"

	"github.com/beego/beego/v2/core/validation"
	beecontext "github.com/beego/beego/v2/server/web/context"
)

func Bind[T any](params *T, ctx *beecontext.Context) error {
	body := ctx.Input.RequestBody

	// 从请求体中解析参数
	if err := json.Unmarshal(body, params); err != nil {
		return err
	}

	err := ValidateParams(params)

	if err != nil {
		return err
	}

	return nil
}

func ValidateParams(params interface{}) error {
	valid := validation.Validation{}

	// 进行数据验证
	b, err := valid.Valid(params)
	if err != nil {
		// 处理验证过程中的错误，比如记录日志等
		return err
	}

	if !b {
		for _, err := range valid.Errors {
			log.Println(err.Key, err.Message)
			return errors.New(err.Message)
		}
	}

	return nil
}

type QuickCallParams struct {
	UserId    int64
	UserIdStr string `json:"user_id"`
}

func (qcp *QuickCallParams) Valid(v *validation.Validation) {
	// 验证UserId是否合法
	var err error
	qcp.UserId, err = strconv.ParseInt(qcp.UserIdStr, 10, 64)

	if err != nil {
		_ = v.SetError("UserId", "用户编号不合法")
		return
	}

	return
}

type CancelQuickCallParams struct {
	UserId    int64
	UserIdStr string `json:"user_id"`
}

func (cqcp *CancelQuickCallParams) Valid(v *validation.Validation) {
	// 验证UserId是否合法
	var err error
	cqcp.UserId, err = strconv.ParseInt(cqcp.UserIdStr, 10, 64)

	if err != nil {
		_ = v.SetError("UserId", "用户编号不合法")
		return
	}

	return
}

type QuickCallRes struct {
	AnchorId    string `json:"anchor_id"`
	Status      int    `json:"status"`
	SubRegionId int    `json:"sub_region_id"`
}

type AnchorPriceInfoRes struct {
	PriceType   int   `json:"price_type"`
	PayPrice    int64 `json:"pay_price"`
	AnchorPrice int64 `json:"anchor_price"`
}
